<?php
/**
 * 用户信息相关接口
 */
require_once("../config/dbconn.php");
 // returnJson(0,'系统升级中，暂时关闭。');
#允许访问列表

// returnJson(0,'系统结算中，所有功能暂时关闭。');
// exit;
// $allow_act = array('login','register','getAccount','getMobileCode','bonus','getuser','logout','editpwd','forgetpwd','sellAndBuy','returnFreezedAccount');
// $act = isset($_POST['act']) ? $_POST['act'] : 'editpwd';#方法

// if(!in_array($act, $allow_act)){
//     returnJson(0,'系统维护中，部分功能暂时关闭。');
// }

$act = isset($_POST['act']) ? $_POST['act'] : '';#方法

$username = isset($_POST['username']) ? trim($_POST['username']) : '';


if($act == 'login'){
    $password = isset($_POST['password']) ? txl_trim($_POST['password']) : '';
    $verifycode = isset($_POST['verifycode']) ? txl_trim($_POST['verifycode']) : '';    //图形验证码
    $mobile = isset($_POST['mobile']) ? txl_trim($_POST['mobile']) : '';
    $code = isset($_POST['code']) ? txl_trim($_POST['code']) : '';
    $status = isset($_POST['status']) ? txl_trim($_POST['status']) : '';
    $source = isset($_POST['source']) ? txl_trim($_POST['source']) : 'trans';   // trans 交易 settlement 结算
    //检测会员状态
    if(empty($username)) returnJson(0,'用户名不能为空');
    $rs = $db->get_one("select id,username,modificationState from wd_users where username='{$username}'");
    if(empty($rs)) returnJson(0,'会员不存在');
    //短信验证码方式登录
    if(isset($status) && $status == 1 && $rs['modificationState'] == 0){
        checkLogin($username,$mobile,$code);
    }elseif(isset($status) && $status ==2 && $rs['modificationState'] == 1){
        //帐号密码方式登录
        if($source == 'trans'){
            checkTC($username,$password);
        }elseif($source == 'settlement'){
            checkTC($username,$password,$verifycode,$source);

        }
    }else{
        returnJson(0,'非法登录');
    }
}elseif($act == 'sellAndBuy'){
    $num = isset($_POST['num']) ? doubleval($_POST['num']) : 0;#出售数量
    $type = isset($_POST['type']) ? intval($_POST['type']) : 1;#类型1出售 2接单
    $ordersn = isset($_POST['ordersn']) ? trim($_POST['ordersn']) : '';#订单编号
    $data = sellAndBuy($username,$num,$type,$ordersn);
}elseif($act == 'out'){
    $to_username = isset($_POST['to_username']) ? trim($_POST['to_username']) : 0;#收款人
    $type = isset($_POST['type']) ? intval($_POST['type']) : 0;#钱包类型 0资产 1交易
    $ordersn = isset($_POST['ordersn']) ? trim($_POST['ordersn']) : '';#订单编号
    $num = isset($_POST['num']) ? doubleval($_POST['num']) : '';#数量
    out($username, $to_username,$type,$ordersn,$num ,$reason);
}elseif($act == 'getAccount'){
    $type = isset($_POST['type']) ? intval($_POST['type']) : 'trade';
    getAccount($username,$type);
}elseif($act == 'frozenAccount'){
    $reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';
    frozenAccount($username,$reason);
}elseif($act == 'getMobileCode'){
    $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
    mobile_code($mobile);
}elseif($act == 'editpwd'){
    $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
//    $oldpwd = isset($_POST['oldpwd']) ? trim($_POST['oldpwd']) : '';
    $newpwd = isset($_POST['newpwd']) ? trim($_POST['newpwd']) : '';
    $confirmpwd = isset($_POST['confirmpwd']) ? trim($_POST['confirmpwd']) : '';
    $code = isset($_POST['code']) ? trim($_POST['code']) : '';
    $type = isset($_POST['type']) ? intval($_POST['type']) : 1;
    editPassword($username,$mobile,$newpwd,$confirmpwd,$code,$type);
}elseif($act == 'forgetpwd'){
    $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
    $newpwd = isset($_POST['newpwd']) ? trim($_POST['newpwd']) : '';
    $confirmpwd = isset($_POST['confirmpwd']) ? trim($_POST['confirmpwd']) : '';
    $code = isset($_POST['code']) ? trim($_POST['code']) : '';
    forgetPwd($username,$mobile ,$newpwd ,$confirmpwd ,$code );
}elseif ($act == 'register'){
    // returnJson(0,"系统结算中，暂时关闭注册功能");
    $nickname=isset($_POST['nickname']) ? trim($_POST['nickname']) : '';
    $tjuser=isset($_POST['tjuser']) ? trim($_POST['tjuser']) : '';
    $gluser=isset($_POST['gluser']) ? trim($_POST['gluser']) : '';
    $pos=isset($_POST['pos']) ? intval($_POST['pos']) : 1;
    $mobile=isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
    $code=isset($_POST['code']) ? trim($_POST['code']) : '';
    register($username,$nickname,$tjuser,$gluser,$pos,$mobile,$code);
}elseif ($act == 'bonus'){
    bonus($username);
}elseif($act == 'returnFreezedAccount'){
    $lists = isset($_POST['lists']) ? $_POST['lists'] : '';
    returnFrozenAccount($lists);
}elseif($act == 'outTJH'){
    $mobile=isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
    $num=isset($_POST['num']) ? trim($_POST['num']) : '';
    $code=isset($_POST['code']) ? trim($_POST['code']) : '';
    $type=isset($_POST['type']) ? trim($_POST['type']) : '';
    $paypwd=isset($_POST['paypwd']) ? trim($_POST['paypwd']) : '';

    outTJH($username,$mobile,$num,$code,$type,$paypwd);
}elseif ($act == 'getuser') {
    $keyword=isset($_POST['keyword']) ? trim($_POST['keyword']) : '';
    getuser($keyword);
}elseif($act == 'unfreezeAccount'){
    unfreezeAccount($username);
}elseif($act == 'unfreezeMoney'){
    $money = isset($_POST['money']) ? doubleval($_POST['money']) : '';#数量
    $ordersn = isset($_POST['ordersn']) ? trim($_POST['ordersn']) : '';#订单编号
    unfreezeMoney($username,$money,$ordersn);
}elseif($act == 'logout'){
    logout();
}elseif($act == 'getRevenue'){
    getRevenue($username);
}elseif($act == 'checkUserInfo'){
    $mobile = isset($_POST['mobile']) ? txl_trim($_POST['mobile']) : '';
    checkUserInfo($username,$mobile);
}elseif($act == 'checkLoginPwd') {
    $password = isset($_POST['password']) ? txl_trim($_POST['password']) : '';
    checkLoginPwd($username,$password);
}elseif($act == 'checkTC'){
    $password = isset($_POST['password']) ? txl_trim($_POST['password']) : '';
    checkTC($username,$password);
}elseif($act == 'cheakUserType'){
    cheakUserType($username);
}elseif ($act == 'cheakUserFutou') {
    cheakUserFutou($username);
}elseif ($act == 'neweditPassword') {
	$password = isset($_POST['password']) ? txl_trim($_POST['password']) : '';
	$source = isset($_POST['source']) ? txl_trim($_POST['source']) : '';
	$userid = isset($_POST['userid']) ? txl_trim($_POST['userid']) : '';
	$mobile = isset($_POST['mobile']) ? txl_trim($_POST['mobile']) : '';
	neweditPassword($userid,$password,$source,$mobile);
}elseif($act == 'batchGetAccount'){
    $lists = isset($_POST['lists']) ? $_POST['lists'] : '';
    batchGetAccount($lists);
}elseif($act == 'getOutType'){
    getOutType();
}elseif($act == 'outImToken'){
    $mobile=isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
    $num=isset($_POST['num']) ? trim($_POST['num']) : '';
    $code=isset($_POST['code']) ? trim($_POST['code']) : '';
    $type=isset($_POST['type']) ? trim($_POST['type']) : '';
    $paypwd=isset($_POST['paypwd']) ? trim($_POST['paypwd']) : '';
    $imtoken= isset($_POST['imtoken']) ? trim($_POST['imtoken']) : '';
    outImToken($username ,$mobile  ,$num ,$code ,$type,$paypwd ,$imtoken);
}elseif($act == 'checkimtoken'){
    $userid=isset($_POST['userid']) ? trim($_POST['userid']) : '';
    checkImToken($userid);
}else{
    die;
}

function checkImToken($userid=''){
    global $db;
    if(empty($userid)) returnJson(0,'会员信息不能为空');
    $rs = $db->get_one("select id,username,modificationState from wd_users where id=$userid");
    if(empty($rs)) returnJson(0,'会员不存在');

    $imtokeninfo = $db->get_one("select * from wd_imtoken where userid=$userid order by addtime desc limit 1");

    if(empty($imtokeninfo)){
        returnJson(1,'该会员不存在申请记录');
    }else{
        if($imtokeninfo['status'] == 2){
            returnJson(2,'上次申请失败，失败原因：'.$imtokeninfo['remark']);
        }else{
            returnJson(1,'该会员可以申请');
        }
    }


}    

/**
 * [登录前验证会员信息]
 * @param  string $username [登录会员名]
 * @return [type]           [description]
 */
function cheakUserType($username=''){
    global $db;
    if(empty($username)) returnJson(0,'会员名称不能为空');
    $rs = $db->get_one("select id,username,modificationState from wd_users where username='{$username}'");
    if(empty($rs)) returnJson(0,'会员不存在');
    returnJson(1,'获取成功',array('status'=>($rs['modificationState']+1)));

}


/**
 * [登录前验证会员信息]
 * @param  string $username [登录会员名]
 * @return [type]           [description]
 */
function cheakUserFutou($username=''){
    global $db;
    if(empty($username)) returnJson(0,'会员名称不能为空');
    $rs = $db->get_one("select id,username,ft_isend from wd_users where username='{$username}'");
    if(empty($rs)) returnJson(0,'会员不存在');
    returnJson(1,'获取成功',array('ft_isend'=>$rs['ft_isend']));

}

/**
 * 验证登录密码
 * @param  string $username [description]
 * @param  string $password [description]
 * @return [type]           [description]
 */
function checkLoginPwd($username='',$password=''){
    global $db;
    if(empty($username)) returnJson(0,'会员名称不能为空');
    if(empty($password)) returnJson(0,'密码不能为空');
    $rs = $db->get_one("select id,username,pwd from wd_users where username='{$username}'");

    if(empty($rs))  returnJson(0,'会员不存在');
    if ($password !=  authcode($rs['pwd'],"DECODE")) {
        returnJson(0,'密码验证失败');
    }else{
        returnJson(1,'密码验证通过');
    }
}

/**
 * 会员登录前信息验证
 * @param  string $username [用户名]
 * @param  string $mobile   [登录手机号]
 * @return [type]           [description]
 */
function checkUserInfo($username='',$mobile=''){
    global $db;
    if(empty($username)) returnJson(0,'会员名称不能为空');
    if(empty($mobile)) returnJson(0,'手机号不能为空');
    //查询用户表，匹配会员名和手机号
    $sql = "select id from wd_users where username='{$username}' and mobile='{$mobile}'";
    $userinfo=$db->get_one($sql);
    if(!isset($userinfo['id'])){
        returnJson(0,'用户名和手机号不匹配');
    }
    //验证通过，发送验证码
    mobile_code($mobile);
}

/**
 * [getRevenue 获取会员近期动态奖收益详情]
 * @param  string $username [用户名]
 * @return [type]           [description]
 */
function getRevenue($username =''){
    global $db,$db_prefix,$curtime;
    $time1 =  strtotime(date('Y-m-d 23:59:59'))-86400;
    $time2 =  strtotime(date('Y-m-d 00:00:00'))-86400;
    //获取会员id
    $userinfo = $db->get_one("select id from wd_users where username='{$username}'");
    if(empty($userinfo)){
        returnJson(0,'会员不存在');
    }
    $price_all = $db->get_one("select sum(price) as c from wd_caiwu where userid={$userinfo['id']} and addtime>{$time2} and addtime<{$time1} and ptype=4 and (type=1 or type=5)");
    if(!isset($price_all['c'])){
        $price =0;
    }else{

        $price = $price_all['c'];
    }
    returnJson(1,'获取成功',array('price'=>$price));
}

/**
 * 冻结账户
 *
 * @return [type] [description]
 */
function frozenAccount($username = null ,$reason = '',$islock= 1){
    global $db,$db_prefix,$curtime;
    if(empty($username)) returnJson(0,'用户信息有误');
    if(empty($reason)) returnJson(0,'冻结原因不能为空');

    $username=str_replace(',','\',\'',$username);
    $sql = "UPDATE {$db_prefix}users SET islock=1,dj_time='".$curtime."',dj_reason ='".$reason."' WHERE username in('".$username."')";
    file_put_contents('./frozenAccount.txt', $sql.PHP_EOL.PHP_EOL,FILE_APPEND);

    $res = $db->query($sql);
    if(!$res){
        returnJson(0,'账户冻结失败');
    }
    returnJson(1,'账户冻结成功');
}

/**
 * 出售、求购交易金额转入冻结金额
 * @return [type] [description]
 */
function sellAndBuy($username = null ,$num = 0,$type = 1,$ordersn = ''){
    global $db,$db_prefix;
    if(empty($username)) returnJson(0,'用户信息有误');
    if($num <= 0) returnJson(0,'交易数量必须大于0');
    if(empty($ordersn)) returnJson(0,'缺少订单编号');
    $user_sql = "select id,islock,username,jyprice from {$db_prefix}users where username = '{$username}'";
    $userinfo = $db->get_one($user_sql);
    if(!$userinfo) returnJson(0,'用户信息有误');
    if($userinfo['jyprice'] < $num) returnJson(0,'交易钱包可用余额不足');
    if($type == 1){
        $memo = '平台交易订单:'.$ordersn.'(出售订单)转入冻结钱包TXL个数为:'.$num;
    }elseif($type == 2){
        $memo = '平台交易订单:'.$ordersn.'(接单同意出售)转入冻结钱包TXL个数为:'.$num;
    }

    hyepricejl($userinfo['id'],$num,8,5,time(),$memo);
    $update_sql = "update {$db_prefix}users set djprice = {$num}+djprice,jyprice = jyprice-{$num} where id = {$userinfo['id']}";
    $res = $db->query($update_sql);
    if($res == 1){
        hyepricejl($userinfo['id'],$num,1,7,time(),'平台交易(交易确认)转入冻结钱包TXL个数为:'.$num);
        returnJson(1,'交易钱包转冻结钱包成功');
    }else{
        returnJson(0,'交易钱包转冻结钱包失败');
    }
}

/**
 * [out 交易成功放行 冻结资金转入买家资产钱包]
 * @param  [type]  $username    [出售方]
 * @param  [type]  $to_username [接收方]
 * @param  integer $type        [转入类型 0 资产 1 交易]
 * @param  string  $ordersn     [订单号]
 * @param  integer $num         [交易金额]
 * @param  string  $reason      [说明]
 * @return [type]               [description]
 */
function out($username = null, $to_username = null,$type = 0,$ordersn = '',$num = 0,$reason = ''){
    file_put_contents('../demo.txt', var_export($_POST,true));
    global $db,$db_prefix,$glo_transfer_ratio;
    if(empty($username)) returnJson(0,'用户信息有误');
    if(empty($to_username)) returnJson(0,'用户信息有误');
    if($num <= 0) returnJson(0,'交易金额需大于0');
    if(empty($ordersn)) returnJson(0,'交易订单编号有误');

    $now_user = $db->get_one("select * from {$db_prefix}users where username = '{$username}'");
    if(!$now_user) returnJson(0,'用户不存在');

    $to_user = $db->get_one("select * from {$db_prefix}users where username = '{$to_username}'");
    if(!$to_user) returnJson(0,'收取人不存在');

    if($now_user['djprice'] < $num ) returnJson(0,'可用冻结金额不足');


    $db->query('start transaction');#开启事物
    try{
        $update_sql = "update {$db_prefix}users set djprice = djprice-{$num} where id = {$now_user['id']}";
        $res1 = $db->query($update_sql);
        if(!$res1){
            throw new Exception('转账失败');
        }
        if($type == 1){
            #如果是交易钱包则扣除平台费率
            #如果交易金额不大于1050，则不扣手续费
            if($num>1050){
                $num = (1-$glo_transfer_ratio/100)*$num;
            }

            $update_sql = "update {$db_prefix}users set jyprice = jyprice+{$num} where id = {$to_user['id']}";
            $res2 = $db->query($update_sql);
            if(!$res2){
                throw new Exception('转账失败');
            }
            $memo = "(订单:{$ordersn})交易成功卖家放行，交易钱包转入{$num}TXL";
            $ptype = 5;
            $type1 = 6;
        }else if($type == 0){
            $update_sql = "update {$db_prefix}users set price = price+{$num},ft_isend=0 where id = {$to_user['id']}";
            $res2 = $db->query($update_sql);
            if(!$res2){
                throw new Exception('转账失败');
            }
            $memo = "(订单:{$ordersn})交易成功卖家放行，资产钱包转入{$num}TXL";
            $ptype = 1;
            $type1 = 1;
        }
        hyepricejl($now_user['id'],"-{$num}",4,7,time(),"(订单:{$ordersn})交易成功放行，从冻结钱包转出{$num}TXL,到买家资产账户");
        hyepricejl($to_user['id'],$num,$type1,$ptype,time(),$memo);
        $db->query('commit');#提交
        returnJson(1,'转账成功');

    }catch(Exception $e){
        $db->query('rollback');#回滚
        returnJson(0,$e->errorMessage());
    }
}


/**
 * 转出钱包余额接口
 * @param  [type] $username [description]
 * @param  [type] $mobile   [description]
 * @param  [type] $num      [description]
 * @param  [type] $code     [description]
 * @param  [type] $paypwd   [description]
 * @return [type]           [description]
 */
function outTJH($username = null,$mobile = null ,$num = null ,$code = null ,$type = null,$paypwd =null){
    global $db,$db_prefix,$curtime;
    if(empty($username)) returnJson(0,'用户名不能为空');
    if(empty($mobile)) returnJson(0,'手机号码不能为空');
    if(empty($paypwd)) returnJson(0,'支付密码不能为空');
    if(empty($type)) returnJson(0,'转出钱包类型不能为空');
    if($num <= 0) returnJson(0,'交易金额需大于0');
    if(empty($code)) returnJson(0,'手机验证码不能为空');
    $userinfo = $db->get_one("select * from {$db_prefix}users where username = '{$username}'");
    if(!$userinfo){
        returnJson(0,'用户与手机号不匹配');
    }
    if($userinfo['mobile'] != $mobile) returnJson(0,'手机号码不正确');
    if(authcode($userinfo['pwd1'],"DECODE")!=$paypwd) returnJson(0,'支付密码不正确');
    checkcode($mobile,$code);
    $field = '';
    $qianbao = '';
    $update_sql = '';
    $cw_type = 0;
    $cw_ptype = 0;
    switch ($type) {
        case 1:
                #交易钱包
                $field = 'jyprice';
                $qianbao = '交易钱包';
                $cw_type = 7;
                $cw_ptype = 5;
            break;
        case 2:
                #购物钱包
                $field = 'gwprice';
                $qianbao = '购物钱包';
                $cw_type = 4;
                $cw_ptype = 6;
            break;
        case 3:
                #释放钱包
                $field = 'sfprice';
                $qianbao = '释放钱包';
                $cw_type = 6;
                $cw_ptype = 2;
            break;
        case 4:
                #算力钱包
                $field = 'slprice';
                $qianbao = '算力钱包';
                $cw_type = 7;
                $cw_ptype = 4;
            break;
        case 5:
                #智能钱包
                $field = 'znprice';
                $qianbao = '智能钱包';
                $cw_type = 5;
                $cw_ptype = 3;
            break;
        case 6:
                #资产钱包
                $field = 'price';
                $qianbao = '资产钱包';
                $cw_type = 7;
                $cw_ptype = 1;
            break;
    }

    if($userinfo[$field] < $num ) returnJson(0,$qianbao.'可用余额不足');
    $update_sql = "update {$db_prefix}users set {$field} = {$field}-{$num} where id = {$userinfo['id']}";
    $res1 = $db->query($update_sql);
    if(!$res1){
        returnJson(0,'转出失败');
    }
    hyepricejl($userinfo['id'],"-{$num}",$cw_type,$cw_ptype,$curtime,"{$qianbao}导出到天机会");
    returnJson(1,'转出成功',array('username'=>$username,'num'=>$num,'type'=>$type,$field=>$num,'mobile'=>$mobile));

}

/**
 * 获取天机会导出钱包类型
 * @return [type] [description]
 */
function getOutType(){
    $arr = array('交易钱包','购物钱包','释放钱包','算力钱包','智能钱包','资产钱包');
    returnJson(1,'成功',$arr);
}

/**
 * 天仓登录验证
 * @param  string $username [description]
 * @param  string $password [description]
 * @return [type]           [description]
 */
function checkTC($username='',$password='',$verifycode='',$source=''){
    global $db;
    if(empty($username)) returnJson(0,'会员名称不能为空');
    if(empty($password)) returnJson(0,'密码不能为空');
    if(!empty($verifycode)){
        if ($_SESSION['lgnrandcode1']!=trim($verifycode)) returnJson(0,'验证码错误');
    }

    $rs = $db->get_one("select id,islock,username,nickname,pwd,regtime,price,gwprice,sfprice,znprice,slprice,jyprice,djprice,mobile,fhstata,modificationState,ft_isend from wd_users where username='{$username}'");

    if(empty($rs))  returnJson(0,'用户名或密码错误');
    if ($password !=  authcode($rs['pwd'],"DECODE")) {
        returnJson(0,'用户名或密码错误');
    }else{
        unset($rs['pwd']);
        if($source =='settlement'){
            if(!isset($_SESSION)){
                session_start();
            }
            $_SESSION['user'] = $rs;
        }
        returnJson(1,'验证通过',$rs);
    }
}

/**
 * 忘记密码
 * @return [type] [description]
 */
function forgetPwd($username = null ,$mobile = null ,$newpwd = null ,$confirmpwd = null,$code = null){
    global $db,$db_prefix;
    if(empty($username)) returnJson(0,'用户名不能为空');
    if(empty($mobile)) returnJson(0,'手机号码不能为空');
    if(empty($newpwd)) returnJson(0,'新密码不能为空');
    // if(empty($confirmpwd)) returnJson(0,'确认密码不能为空');
    // if($newpwd != $confirmpwd) returnJson(0,'密码不一致');
    if(empty($code)) returnJson(0,'手机验证码不能为空');

    $userinfo = $db->get_one("select * from {$db_prefix}users where username = '{$username}' and mobile = '{$mobile}'");
    if(!$userinfo){
        returnJson(0,'用户与手机号不匹配');
    }
    checkcode($mobile,$code);
    $newpwd1 = authcode($newpwd,'ENCODE');
    $res = $db->update("{$db_prefix}users",array('pwd'=>$newpwd1),"id = {$userinfo['id']}");
    if($res){
        returnJson(1,'密码修改成功');
    }else{
        returnJson(0,'密码修改失败');
    }
}
/**
 * [bonus 奖金明细]
 * @param  string $username [description]
 * @return [type]           [description]
 */
function bonus($username=''){
    global $db,$db_prefix;
    if(empty($username)) returnJson(0,'用户名不能为空');
    $userinfo = $db->get_one("select id from {$db_prefix}users where username = '".trim($username)."'");

    if(empty($userinfo)){
        returnJson(0,'用户不存在');
    }
    $sql="SELECT * from {$db_prefix}caiwu where userid = '".$userinfo['id']."' and ((ptype='3'and type='1') or (ptype='4'and (type='1'or type='5'))) ORDER BY addtime DESC";
    $caiwulist = $db->get_all($sql);
    $caiwudata = array();
    foreach ($caiwulist as $k=>$v){
        $strtime = date('Ymd',$v['addtime']);
        $caiwudata[$strtime][$k] = $v;
    }

    $caiwuresult = array();
    foreach ($caiwudata as $key => $value){
        $caiwuresult[$key]['price1'] = 0;
        $caiwuresult[$key]['price2'] = 0;
        $caiwuresult[$key]['price3'] = 0;
        foreach ($value as $s_key=>$s_value){
            $caiwuresult[$key]['priceall'] += $s_value['price'];
            $caiwuresult[$key]['time'] = date('m-d',$s_value['addtime']);
            if($s_value['ptype'] == 3){
                $caiwuresult[$key]['price1'] += $s_value['price'];
            }else if($s_value['ptype'] == 4 && $s_value['type'] == 1){
                $caiwuresult[$key]['price2'] += $s_value['price'];
            }else if($s_value['ptype'] == 4 && $s_value['type'] == 5){
                $caiwuresult[$key]['price3'] += $s_value['price'];
            }
        }
    }
    returnJson(1,'数据获取成功',$caiwuresult);
}

/**
 * [returnFrozenAccount 清理挂单]
 * @param  string $lists [会员信息]
 * @return [type]        [成功信息返回]
 */
function returnFrozenAccount($lists=''){
    global $db,$db_prefix,$curtime;
    if (!is_array($lists)) {
        returnJson(0,'更新数据不能为空');
    }
    file_put_contents('frozenAccount.txt','参数:'.serialize($lists).'======='.PHP_EOL, FILE_APPEND);
    //遍历该数组
    foreach ($lists as $key => $value) {
        // 会员验证
        $sql = "select id,username,djprice,islock from {$db_prefix}users where username='".trim($key)."'";
        $row = $db->get_one($sql);
        if ($row['djprice'] < $value ) {
            // returnJson(0,'会员:'.$row['username'].'的冻结钱包余额不足');
            file_put_contents('frozenError.txt',$key.'======='.PHP_EOL, FILE_APPEND);

            continue;
        }
        $db->query('start transaction');#开启事物
        try {
            //验证通过
            $rs = $db->query("update {$db_prefix}users set jyprice=jyprice+{$value},djprice=djprice-{$value} where username='".$key."'");
            if(!$rs){
                throw new Exception('转账失败');
            }
            //交易钱包财务日志
            $e_userid = $row['id'];
            $e_price = $value;
            $e_memo = "交易系统清理挂单，交易钱包转入TXL：".$value;
            hyepricejl($e_userid, $e_price, 9, 5, $curtime, $e_memo);

            //冻结钱包财务日志
            $e_userid = $row['id'];
            $e_price = -$value;
            $e_memo = "交易系统清理挂单，冻结钱包转出TXL：".$value;
            hyepricejl($e_userid, $e_price, 5, 7, $curtime, $e_memo);

            $db->query('commit');#提交
        }catch(Exception $e){
            $db->query('rollback');#回滚
            returnJson(0,$e->errorMessage());
        }
    }
    returnJson(1,'执行成功');

}
/**
 * [unfreezeMoney 解除资金冻结]
 * @param  string $username [冻结会员]
 * @param  string $money    [冻结资金]
 * @return [type]           [description]
 */
function unfreezeMoney($username='',$money='',$ordersn = ''){
    global $db,$db_prefix,$curtime;
    if(empty($username)){
        returnJson(0,'会员名称不能为空');
    }
    if($money <= 0){
        returnJson(0,'冻结资金必须大于0');
    }
    if(empty($ordersn)){
        returnJson(0,'订单编号不能为空');
    }
    //查询会员
    $sql = "select username,islock,id,djprice from {$db_prefix}users where username= '{$username}'";
    $res = $db->get_one($sql);
    $db->free_result();
    if(empty($res)){
        returnJson(0,'会员信息不存在');
    }else{
        if($res['djprice'] < $money){
            returnJson(0,'可用冻结金额不足');
        }
        $update_sql = "update {$db_prefix}users set islock = 0 , djprice = djprice-{$money} ,jyprice = jyprice+{$money} where id = {$res['id']}";
        $update_res = $db->query($update_sql);
        if($update_res){
            $e_memo = "(订单:{$ordersn})交易失败解除冻结资金，冻结钱包转出TXL：".$money;
            hyepricejl($res['id'], -$money, 6, 7, $curtime, $e_memo);
            $e_memo = "(订单:{$ordersn})交易失败解除冻结资金，交易钱包转入TXL：".$money;
            hyepricejl($res['id'], $money, 13, 5, $curtime, $e_memo);
            returnJson(1,'解除冻结资金成功');
        }else{
            returnJson(0,'解除冻结资金失败');
        }
    }

}
/**
 * [unfreezeAccount 解除冻结账户]
 * @param  string $username [冻结会员]
 * @return [type]           [description]
 */
function unfreezeAccount($username=''){
    global $db,$db_prefix,$curtime;
    if(empty($username)){
        returnJson(0,'会员名称不能为空');
    }
    //查询会员
    $sql = "select username,islock,id,djprice from {$db_prefix}users where username= '{$username}'";
    $res = $db->get_one($sql);
    $db->free_result();
    if(empty($res)){
        returnJson(0,'会员信息不存在');
    }else{
        if($res['islock']){
            $update_sql = "update {$db_prefix}users set islock = 0  where id = {$res['id']}";
            $update_res = $db->query($update_sql);
            if($update_res){
                returnJson(1,'解除冻结账户成功');
            }else{
                returnJson(0,'解除冻结账户失败');
            }
        }else{
            returnJson(0,'此会员未被冻结');
        }
    }

}


/**
 * 获取用户信息
 * @param  string $keyword [description]
 * @return [type]          [description]
 */
function getuser($keyword=''){
    global $db,$db_prefix;
    if (empty($keyword)) {
        returnJson(0,'要查询的信息不能为空');
    }
    $sql = "select islock,username,nickname,regtime,djprice,dj_reason,dj_time,mobile,fhstata,modificationState,ft_isend from {$db_prefix}users where username='".trim($keyword)."'";
    $res = $db->get_all($sql);
    $db->free_result();
    if (empty($res)) {
        returnJson(0,'会员信息不存在');
    }else{
        returnJson(1,'查询成功',$res);
    }
}


/*退出登录*/
function logout(){
    unset($_SESSION['user']);
    returnJson(1,'退出成功','http://js.hscep.top/#/login');

}




/**
 * 转出钱包余额接口
 * @param  [type] $username [description]
 * @param  [type] $mobile   [description]
 * @param  [type] $num      [description]
 * @param  [type] $code     [description]
 * @param  [type] $paypwd   [description]
 * @return [type]           [description]
 */
function outImToken($username = null,$mobile = null ,$num = null ,$code = null ,$type = null,$paypwd =null,$imtoken=''){
    global $db,$db_prefix,$curtime;
    if(empty($username)) returnJson(0,'用户名不能为空');
    // if(empty($mobile)) returnJson(0,'手机号码不能为空');
    if(empty($imtoken)) returnJson(0,'ImToken不能为空');
    if(mb_strlen($imtoken)<=24) returnJson(0,'ImToken钱包地址格式有误');
    // if(empty($paypwd)) returnJson(0,'支付密码不能为空');
    if(empty($type)) returnJson(0,'转出钱包类型不能为空');
    if($num <= 0) returnJson(0,'交易金额需大于0');
    // if(empty($code)) returnJson(0,'手机验证码不能为空');
    $userinfo = $db->get_one("select * from {$db_prefix}users where username = '{$username}'");
    // if(!$userinfo){
    //     returnJson(0,'用户与手机号不匹配');
    // }
    // if($userinfo['mobile'] != $mobile) returnJson(0,'手机号码不正确');
    #查看是否有未处理的申请
    $is_ok = $db->get_one("select * from {$db_prefix}imtoken where userid = {$userinfo['id']} and status = 0");
    if($is_ok) returnJson(0,'您还有未处理的申请,不能再次提交');
    // if(authcode($userinfo['pwd1'],"DECODE")!=$paypwd) returnJson(0,'支付密码不正确');
    // checkcode($mobile,$code);
    $field = '';
    $qianbao = '';
    $update_sql = '';
    $cw_type = 0;
    $cw_ptype = 0;
    switch ($type) {
        case 1:
                #交易钱包
                $field = 'jyprice';
                $qianbao = '交易钱包';
                // $cw_type = 16;
                // $cw_ptype = 5;
                $wallet_type = 1;
            break;
    }

    if($userinfo[$field] < $num ) returnJson(0,$qianbao.'可用余额不足');
    // $update_sql = "update {$db_prefix}users set {$field} = {$field}-{$num} where id = {$userinfo['id']}";
    // $res1 = $db->query($update_sql);
    // if(!$res1){
    //     returnJson(0,'转出失败');
    // }
    // hyepricejl($userinfo['id'],"-{$num}",$cw_type,$cw_ptype,$curtime,"{$qianbao}导出到ImToken");

    //insert 插入到 wd_imtoken表
    $imtoken_insert['userid']=$userinfo['id'];
    $imtoken_insert['imtoken']=$imtoken;
    $imtoken_insert['price']=$num;
    $imtoken_insert['status']=0;
    $imtoken_insert['wallet_type']=$wallet_type;
    $imtoken_insert['addtime']=$curtime;
    $db->insert("{$db_prefix}imtoken",$imtoken_insert);
    returnJson(1,'提交成功',array('username'=>$username,'num'=>$num,'type'=>$type,$field=>$num,'mobile'=>$mobile));

}
